package de.karlNet.gifSocket;

import java.awt.image.BufferedImage;
import java.util.concurrent.CountDownLatch;

public class ScreenshotBuffer {
	private volatile int currentImage = 0;
	private final BufferedImage[] images = new BufferedImage[5];
	private volatile int mostCurrentImage = 0;
	private volatile boolean hasNew = false;
	private CountDownLatch countDownLatch = new CountDownLatch(1);
	private AnimatedGifEncoder animatedGifEncoder;

	public ScreenshotBuffer() {
		for (int i = 0; i < this.images.length; i++) {
			this.images[i] = new BufferedImage(1024, 768,
					BufferedImage.TYPE_INT_RGB);
		}
	}

	public ScreenshotBuffer(AnimatedGifEncoder animatedGifEncoder) {
		this.animatedGifEncoder = animatedGifEncoder;
	}

	public BufferedImage getMostCurrentImage() {
		try {
			countDownLatch.await();
			countDownLatch = new CountDownLatch(1);
		} catch (InterruptedException e1) {
			return new BufferedImage(1024, 768, BufferedImage.TYPE_INT_RGB);
		}

		if (this.currentImage <= 0) {
			return this.images[0];
		}
		return this.images[this.currentImage - 1];
	}

	public void addScreenshot(BufferedImage bufferedImage) {
		if (this.animatedGifEncoder != null) {
			this.animatedGifEncoder.addFrame(bufferedImage);
			return;
		}

		countDownLatch.countDown();
		this.images[this.currentImage] = bufferedImage;
		this.currentImage = (this.currentImage + 1) % this.images.length;
	}
}
